package com.hzhc.aliyun;

import com.aliyun.ocr20191230.models.RecognizePdfResponse;
import com.aliyun.ocr20191230.models.RecognizePdfResponseBody;
import com.aliyun.ocr20191230.models.RecognizePdfResponseBody.RecognizePdfResponseBodyData;
import com.aliyun.ocr20191230.models.RecognizePdfResponseBody.RecognizePdfResponseBodyDataWordsInfo;
import com.hzhc.utils.PDFUtils;
import com.hzhc.vo.CrfNoVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @ClassName: RecognizePdf
 * @Description:
 * @version 1.0
 * @author: duanhm
 * @Date: 2024/08/12 11:41:05
 * 
 */
@Component
@Log4j2
public class RecognizePdf {
	private static String ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI5tGeucofToG5GmpqAg4W";
	private static String ALIBABA_CLOUD_ACCESS_KEY_SECRET = "65Y35MyUxgq6vY8iEGRy2Q0z0uksCm";


	public static String sydPDfSplitFolader;

	public static String sydImageFolader;

	public static String sydImageAccessPath;

	@Value("${file.sydPDfSplitFolader}")
	public void setSydPDfSplitFolader(String sydPDfSplitFolader) {
		RecognizePdf.sydPDfSplitFolader = sydPDfSplitFolader;
	}

	@Value("${file.sydImageFolader}")
	public void setSydImageFolader(String sydImageFolader) {
		RecognizePdf.sydImageFolader = sydImageFolader;
	}

	@Value("${file.sydImageAccessPath}")
	public void setSydImageAccessPath(String sydImageAccessPath) {
		RecognizePdf.sydImageAccessPath = sydImageAccessPath;
	}



	public static com.aliyun.ocr20191230.Client createClient(String accessKeyId, String accessKeySecret)
			throws Exception {
		/*
		 * 初始化配置对象com.aliyun.teaopenapi.models.Config Config对象存放
		 * AccessKeyId、AccessKeySecret、endpoint等配置
		 */
		com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
				.setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret);
		// 访问的域名
		config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
		return new com.aliyun.ocr20191230.Client(config);
	}

//	public static void main(String[] args_) throws Exception {
//		String filePath = "C://Users//Administrator//Desktop//6.17耐火材料10运单.pdf";
//		String filePath = "/Users/wuxiaoke/Downloads/a/6.17耐火材料10运单.pdf";
//		List<CrfNoVo> list = AliCloudAnalyzePDF(Files.newInputStream(new File(filePath).toPath()),new File(filePath).getName());
//		log.info(list.toString());
		// log.info(verifyEnd("制单日期：2024-06-16"));

//	}

	/**
	 * @throws Exception
	 *
	 */
	public static List<CrfNoVo> AliCloudAnalyzePDF(MultipartFile multipartFile, String fileName) throws Exception {
		//设置日期格式
		DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		//当地日期转换
		String dayFormat = LocalDate.now().format(formatters);
		// 创建AccessKey ID和AccessKey
		// Secret，请参考https://help.aliyun.com/document_detail/175144.html
		// 如果您使用的是RAM用户的AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
		// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
		String accessKeyId = ALIBABA_CLOUD_ACCESS_KEY_ID;
		String accessKeySecret = ALIBABA_CLOUD_ACCESS_KEY_SECRET;
		com.aliyun.ocr20191230.Client client = RecognizePdf.createClient(accessKeyId, accessKeySecret);
		// 场景一，使用本地文件
//		InputStream inputStream = new FileInputStream(new File(pdfFilePath));
		// 场景二，使用任意可访问的url
		// URL url = new URL(
		// "https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/ocr/RecognizePdf/RecognizePdf1.pdf");
		// InputStream inputStream = url.openConnection().getInputStream();
		com.aliyun.ocr20191230.models.RecognizePdfAdvanceRequest recognizePdfAdvanceRequest = new com.aliyun.ocr20191230.models.RecognizePdfAdvanceRequest()
				.setFileURLObject(multipartFile.getInputStream());
		com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
		List<CrfNoVo> crfNolist = new ArrayList<CrfNoVo>();
		try {
			RecognizePdfResponse recognizePdfResponse = client.recognizePdfAdvance(recognizePdfAdvanceRequest, runtime);
			// 获取整体结果
			// System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(recognizePdfResponse)));
			// 获取单个字段
			RecognizePdfResponseBody obj = recognizePdfResponse.getBody();
			RecognizePdfResponseBodyData data = obj.getData();
			// 获取页面数
			// Long pageSize = data.getPageIndex();
			Long currPage = (long) 1;
			List<RecognizePdfResponseBodyDataWordsInfo> wordslist = data.getWordsInfo();
			CrfNoVo vo = null;
			List<String> cntrList = null;
			for (int i = 0; i < wordslist.size(); i++) {
				RecognizePdfResponseBodyDataWordsInfo wordinfo = wordslist.get(i);
				String word = wordinfo.getWord();
				Long x = wordinfo.getX();
				Long y = wordinfo.getY();

				log.debug("i={}={}=x={}=y={}", i, word, x, y);
				/// if (StrUtil.isNotBlank(word)) {
				//
				// 获取底单号"x":1273,"y":162x=1273=y=162
				word = word.replaceAll("\\s*", "");
				if (x == 1273) {
					// log.info(word);
					if (y == 162) {
						vo = new CrfNoVo();
						vo.setRfbnum(word);
						vo.setPageIndex(currPage);
						cntrList = new ArrayList<String>();
					}
				}
				// String billNo=
				// 获取集装箱号
				if (verifyCntrCode(word)) {
					// log.info(word);
					cntrList.add(word);
				}
				// }
				// 判断是否最后位置，“制单日期”结束
				if (verifyEnd(word)) {
					currPage++;
					// log.info(vo.toString());
					vo.setSourcePdfdir(fileName);
					vo.setCntrList(cntrList);
					//截取pdf文件到临时文件夹中
					String destFolder = sydPDfSplitFolader + File.separator+ dayFormat;
					String destPath = sydPDfSplitFolader + File.separator+ dayFormat + File.separator + fileName.replace(".pdf","")+"-"+currPage+".pdf";
					File fileFolder = new File(destFolder);
					if(!fileFolder.exists()) {
						boolean b =fileFolder.mkdirs();
					}
					String path = PDFUtils.splitPdf(vo.getPageIndex().intValue(), multipartFile.getInputStream(), destPath);
                    File file = null;
                    if (path != null) {
                        file = new File(path);
						//转换图片
						String imageName = fileName.replace(".pdf","")+ "_" + vo.getPageIndex() +".png";
						String targetFolder = sydImageFolader + File.separator+ dayFormat;
						String targetPath = sydImageFolader +File.separator + dayFormat + File.separator + imageName;
						File targetFfileFolder = new File(targetFolder);
						if(!targetFfileFolder.exists()) {
							boolean b =targetFfileFolder.mkdirs();
						}
						boolean b = PDFUtils.pdfFileToImage(file, targetPath);
						if(b){
							vo.setSubPdfdir(sydImageAccessPath.replaceAll("\\*", "") + dayFormat+ File.separator + imageName);
							crfNolist.add(vo);
						}
                    }
				}
				// wordslist.get(i).getWord();
			}
			// System.out.println(com.aliyun.teautil.Common.toJSONString(data));
			// System.out.println(recognizePdfResponse.getBody());
		} catch (com.aliyun.tea.TeaException teaException) {
			// 获取整体报错信息
			log.info(com.aliyun.teautil.Common.toJSONString(teaException));
			// 获取单个字段
			log.info(teaException.getCode());
		}
		return crfNolist;
	}

	/**
	 * 验证是否pdf结束
	 *
	 * @param content
	 * @return
	 */
	private static boolean verifyEnd(String content) {
		String pattern = "制单日期.*";
		boolean isMatch = Pattern.matches(pattern, content);
		// System.out.println(isMatch);
		return isMatch;
	}

	/**
	 *
	 * @param strCode
	 * @return
	 */
	public static boolean verifyCntrCode(String strCode) {
		boolean result = true;
		try {
			if (strCode.length() != 11) {
				return false;
			}
			String regex = "^[A-Za-z][A-Za-z0-9]{10}$";
			result = strCode.matches(regex);
		} catch (Exception e) {
			result = false;
		}
		return result;
	}

}
